<script setup lang='ts'>
import { SearchForm, SearchTable } from '@fl/components'
import { cloneDeep } from 'lodash-es'
import { OPERATE_STATE } from './constant'
import { useUserStore } from '@fl/store/modules/user'
import type { VxeGridProps, VxePagerEvents } from 'vxe-table'
import { useDeleteContract, useExportContractList, useGetContractList, useInitContract, useStopContract } from '@fl/api/mall-api'

const userStore = useUserStore()

const { meta: { isAdmin }, path } = useRoute()

const { push } = useRouter()

const userInfo = computed(() => userStore.getUserInfo)

const isSupplier = computed(() => userInfo.value?.sysUser?.roles?.[0]?.roleKey === 'supplier')

const { mutate: deleteMutate, isPending: deletePending } = useDeleteContract()

const { mutate: initMutate } = useInitContract()

const { mutate: stopMutate, isPending: stopPending } = useStopContract()

const { mutate: exportMutate, isPending: exportPending } = useExportContractList()

const tableRef = ref()

const initialState = {
    status: '',
    agreementName: '',
    partyA: '',
    partyB: '',
    agreementCode: '',
    initiationTime: [],
}

const operateStateOptions = Object.entries(OPERATE_STATE)
    .filter(([value]) => {
        const numericValue = Number(value)
        if (isAdmin) {
            return numericValue !== 0
        }
        if (isSupplier.value) {
            return ![0, 1].includes(numericValue)
        }
        return true // 其他情况不过滤
    })
    .map(([value, label]) => ({
        value: Number(value),
        label,
    }))

const state = ref(cloneDeep(initialState))

const initialPage = {
    currentPage: 1,
    pageSize: 10,
    total: 0,
}

const tablePage = ref(cloneDeep(initialPage))

const columns = computed(() => {
    if (isAdmin) {
        return [
            {
                label: '状态',
                prop: 'status',
                valueType: 'select',
                options: operateStateOptions,
            },
            {
                label: '合同名称',
                prop: 'agreementName',
            },
            {
                label: '合同编号',
                prop: 'agreementCode',
            },
            {
                label: '甲方',
                prop: 'partyA',
            },
            {
                label: '乙方',
                prop: 'partyB',
            },
            {
                label: '发起时间',
                prop: 'initiationTime',
                valueType: 'date-picker',
                fieldProps: {
                    type: 'daterange',
                    format: 'YYYY-MM-DD',
                    valueFormat: 'YYYY-MM-DD',
                },
            },
        ]
    }
    return [
        {
            label: '状态',
            prop: 'status',
            valueType: 'select',
            options: operateStateOptions,
        },
        {
            label: '合同名称',
            prop: 'agreementName',
        },
        {
            label: isSupplier.value ? '甲方' : '乙方',
            prop: isSupplier.value ? 'partyA' : 'partyB',
        },
        {
            label: '合同编号',
            prop: 'agreementCode',
        },
        {
            label: '发起时间',
            prop: 'initiationTime',
            valueType: 'date-picker',
            fieldProps: {
                type: 'daterange',
                format: 'YYYY-MM-DD',
                valueFormat: 'YYYY-MM-DD',
            },
        },
    ]
})

const params = computed(() => {
    const { initiationTime, ...rest } = state.value
    return {
        ...rest,
        agreementType: 2,
        startDate: initiationTime?.[0] ? initiationTime[0] : '',
        endDate: initiationTime?.[1] ? initiationTime[1] : '',
        page: tablePage.value.currentPage,
        size: tablePage.value.pageSize,
    }
})

const { data, isLoading } = useGetContractList(params, isAdmin)

const loading = computed(() => isLoading.value || deletePending.value || stopPending.value)

const tableData = ref<any[]>([])

const minWidth = 200
const gridOptions = computed<VxeGridProps>(() => {
    return {
        columns: [
            { type: 'seq', title: '序号', width: 50 },
            { field: 'agreementCode', title: '合同编号', minWidth },
            { field: 'agreementName', title: '合同名称', minWidth, slots: { default: 'agreementName' } },
            { field: 'partyA', title: '甲方', visible: isSupplier.value || isAdmin, minWidth: 130 },
            { field: 'partyB', title: '乙方', visible: !isSupplier.value || isAdmin, minWidth: 150 },
            { slots: { default: 'validityPeriod' }, title: '合同有效期', minWidth },
            { field: 'initiationTime', title: '发起时间', minWidth },
            { field: 'contractPrice', title: '合同金额(元)', minWidth: 150, visible: isAdmin },
            {
                field: 'status',
                title: '状态',
                minWidth: 120,
                formatter(params) {
                    return OPERATE_STATE[params.cellValue]
                },
            },
            { slots: { default: 'opreate' }, title: '操作', fixed: 'right', width: 250, visible: !isAdmin },
        ],
        maxHeight: 650,
    }
})

function submitSearch(values: any) {
    state.value = cloneDeep(values)
    tablePage.value.currentPage = 1
}

function resetSearch() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initialPage)
}

const handlePageChange: VxePagerEvents.PageChange = ({ currentPage, pageSize }) => {
    tablePage.value.currentPage = currentPage
    tablePage.value.pageSize = pageSize
}

function handleAdd() {
    push('contract-add')
}

function showEditAndDel(row: any) {
    if (isSupplier.value) {
        return false
    }
    return ['草稿'].includes(OPERATE_STATE[row.status]) && row.flag === 1
}

function showOrderAndStop(row: any) {
    if (isSupplier.value) {
        return false
    }
    return ['已生效'].includes(OPERATE_STATE[row.status])
}

function initiatedText(row: any) {
    if (row.flag !== 1) {
        return '查看'
    }
    if (isSupplier.value) {
        if (['待乙方签约'].includes(OPERATE_STATE[row.status])) {
            return '签约'
        }
        return '查看'
    }

    if (['待甲方发起'].includes(OPERATE_STATE[row.status])) {
        return '发起'
    }
    if (['草稿'].includes(OPERATE_STATE[row.status])) {
        return '编辑'
    }
    if (['待甲方签约'].includes(OPERATE_STATE[row.status])) {
        return '签约'
    }
    return '查看'
}
function handleInitiated(row: any) {
    if (!['待甲方发起'].includes(OPERATE_STATE[row.status])) {
        return goView(row.id)
    }
    ElMessageBox.confirm('是否确认发起合同?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        initMutate(row.id, {
            onSuccess: () => {
                goView(row.id)
            },
        })
    }).catch(() => {
    })
}

function handleDelete(id: string) {
    ElMessageBox.confirm('是否确认删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        deleteMutate(id, {
            onSuccess: () => {
                ElMessage.success('操作成功')
            },
        })
    }).catch(() => {
    })
}

function handleStop(row: any) {
    ElMessageBox.confirm('是否确认停用?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        stopMutate(row.id, {
            onSuccess: () => {
                ElMessage.success('操作成功')
            },
        })
    }).catch(() => {
    })
}

function goView(id: string) {
    push(`${path}/${id}`)
}

function addOrder(id: string) {
    push(`/purchase-pages/purchase-order-management/add-order/${id}`)
}

function exportFile() {
    exportMutate(unref(params), {
        onSuccess: (res: any) => {
            const objectUrl = URL.createObjectURL(res)
            location.href = objectUrl
            URL.revokeObjectURL(objectUrl)
        },
    })
}

watchEffect((() => {
    if (data.value) {
        tableData.value = cloneDeep(data.value?.records || [])
        tablePage.value.total = data.value.total ?? 0
    }
}))
</script>

<template>
    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchForm v-bind="state"
                    :columns="columns"
                    submit-text="查询"
                    @reset="resetSearch"
                    @submit="submitSearch"
        />
    </ElCard>

    <ElCard class="mb-20"
            shadow="never"
    >
        <SearchTable ref="tableRef"
                     v-bind="gridOptions"
                     v-model:pager="tablePage"
                     :seq-config="{ startIndex: (tablePage.currentPage - 1) * tablePage.pageSize }"
                     :data="tableData"
                     :loading="loading"
                     @page-change="handlePageChange"
        >
            <template #toolbar_buttons>
                <ElButton v-if="!isSupplier && !isAdmin"
                          type="primary"
                          @click="handleAdd"
                >
                    新增合同
                </ElButton>

                <ElButton v-if="isAdmin"
                          type="primary"
                          :loading="exportPending"
                          @click="exportFile"
                >
                    导出
                </ElButton>
            </template>

            <template #agreementName="{ row }">
                <span v-if="!isAdmin">{{ row.agreementName }}</span>

                <ElButton v-else
                          text
                          type="primary"
                          @click="goView(row.id)"
                >
                    {{ row.agreementName }}
                </ElButton>
            </template>

            <template #validityPeriod="{ row }">
                <span v-if="row.startDate && row.endDate"> {{ row.startDate }} 至 {{ row.endDate }}</span>
            </template>

            <template #opreate="{ row }">
                <ElButton text
                          type="primary"
                          @click="handleInitiated(row)"
                >
                    {{ initiatedText(row) }}
                </ElButton>

                <ElButton v-if="showEditAndDel(row)"
                          text
                          type="primary"
                          @click="handleDelete(row.id)"
                >
                    删除
                </ElButton>

                <ElButton v-if="showOrderAndStop(row)"
                          text
                          type="primary"
                          @click="addOrder(row.id)"
                >
                    下单
                </ElButton>

                <ElButton v-if="showOrderAndStop(row)"
                          text
                          type="primary"
                          @click="handleStop(row)"
                >
                    停用
                </ElButton>
            </template>
        </SearchTable>
    </ElCard>
</template>

<style lang="scss" scoped>
.el-button + .el-button {
    margin-left: 0;
}
</style>
